// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {

  switch (event.action) {
    case 'publish': return  publish(event)
    case 'list':return list(event)
    case 'del' :return del(event)
    case 'edit' :return edit(event)
    case 'apply':return apply(event)
    case 'quit':return quit(event)
    case 'accept' :return accept(event)
    case 'changeStatus': return changeStatus(event)
    default: return Promise.reject("unknown action")
  }
}

async function publish(event){

  var params = event.data
  var now = new Date()
  return new Promise((reslove,reject)=>{
     db.collection('player').add({
      data:{
        ...params,
        openid:cloud.getWXContext().OPENID,
        createTime:now
      }
    })
    .then(res=>{
      reslove({code:200,message:"创建队伍成功",data:res})
    })
    .catch(err=>{
      reject({code:300,message:"创建队伍失败",data:err})
    })
  })
}

async function del(event){
  var id = event.id
  return new Promise((reslove,reject)=>{
     db.collection('player').doc(id).update({
      data:{
        status:'del'
      }
    })
    .then(res=>{
      reslove({code:200,message:"更新队伍信息成功",data:res})
    })
    .catch(err=>{
      reject({code:300,message:"更新队伍信息失败",data:err})
    })
    
  })
}

async function edit(event){
  var id = event.id
  var params = event.data
  return new Promise((reslove,reject)=>{
     db.collection('player').doc(id).update({
      data:{
        ...params
      }
    })
    .then(res=>{
      reslove({code:200,message:"删除比赛成功",data:res})
    })
    .catch(err=>{
      reject({code:300,message:"删除比赛失败",data:err})
    })
    
  })
}

async function list(event){
  var status = event.status == 'all'?_.eq('need'):event.status
  var status = event.status =='waitAndReject'?_.eq('wait').or(_.eq('reject')):status
  var type = event.type 
  var id = event.id==''?true:event.id
  var Myopenid = event.openid
  console.log(type)
  return new Promise((reslove,reject)=>{
    if(type=='join'){
       db.collection('player').aggregate()
      .match({
        mates:_.all([
          _.elemMatch({
            openid:Myopenid
          })
        ])
      }).end()
      .then(res=>{
        reslove({code:200,message:"获得等待招募信息成功",data:res})
      })
      .catch(err=>{
        reject({code:300,message:"获得等待招募信息失败",data:err})
      })
    }
    else if(type=='create'){
      console.log("debugGreat")
      console.log(Myopenid)
      status = event.status == 'all'?_.eq('need').or(_.eq('wait')).or(_.eq('reject')):status
       db.collection('player').aggregate()
      .sort({createTime:-1})
      .match({
        openid:Myopenid,
        status:status
      }).end()
      .then(res=>{
        reslove({code:200,message:"获得等待招募信息成功",data:res})
      })
      .catch(err=>{
        reject({code:300,message:"获得等待招募信息失败",data:err})
      })
    }
    else{
      db.collection('player').aggregate()
      .sort({createTime:-1})
      .match({
        status:status,
        contestID:id
      }).end()
      .then(res=>{
        reslove({code:200,message:"获得等待招募信息成功",data:res})
      })
      .catch(err=>{
        reject({code:300,message:"获得等待招募信息失败",data:err})
      })
      
    }
  
     
  })

}

async function apply(event){ 
  var {teamID,avatarUrl,openid,nickName,leaderID} = event.data
  var status = "queue"
  var mate = {avatarUrl,openid,nickName,status,initiator}
  console.log(event.data)
  var applyInfo = {teamID,avatarUrl,openid,nickName,leaderID,status}

  const result = await db.runTransaction(async transaction=>{
    
    const t1 = db.collection('player').doc(teamID).update({
      data:{
        mates:_.push(mate)
      }
    })
     
   
    return {code:200,message:"邀请",data:{t1}}
  })
  
  return result
}

async function accept(event){

  var openid = event.openid
  var {status,openid,teamID,ACID} = event.data

  const result = await db.runTransaction(async transaction=>{
    const t1 = db.collection('player')
    .where({
      '_id':teamID,
      'mates.openid':openid
    })
    .update({
      data:{
       'mates.$.status':_.set(status)
      }
    })
     
    const t2 = await db.collection('apply')
    .doc(ACID)
    .update({
      data:{
        status:status
      }
    })
    return {code:200,message:"同意加入队伍成功",data:{t1}}
  })
  return result

}

async function quit(event){
  var teamID = event.teamID
  return new Promise((reslove,reject)=>{
     db.collection('player').doc(teamID)
    .update({
      data:{
        mates:_.pull({
          openid:cloud.getWXContext().OPENID
        })
      }
    })
    .then(res=>{
      reslove({code:200,message:"退出队伍成功",data:res})
    })
    .catch(err=>{
      reject({code:300,message:"退出队伍失败",data:err})
    })

  })
}
async function changeStatus(event){
  var teamID =  event.teamID
  var status =  event.status
  return new Promise((reslove,reject)=>{
    db.collection('player').doc(teamID)
    .update({
      data:{
        status:status
      }
    })
    .then(res=>{
      reslove({code:200,message:"转换成功",data:res})
    })
    .catch(err=>{
      reject({code:300,message:"转换失败",data:err})
    })
  })
}